/**
 * config start
 */
const path = require('path');
const chalk = require('chalk');
const webpack = require('webpack');
const getDevConfig = require('./dev.config').getConfig;
const getProductionConfig = require('./production.config').getConfig;

const config = require('./config');

const { __DEV__, __PROD__ } = config.globals;
const APP_ENTRY = path.resolve(__dirname, './client/index.jsx');
let buildRunning = false;
let startTime = 0;


let webpackConfig = {
    entry: {
    },
    resolve: {
        alias: {
            '~projectCommon': path.resolve(__dirname, './common'),
        },
        modules: [
            path.join(__dirname, './client'),
            './',
            'node_modules',
        ],
        extensions: ['.web.js', '.js', 'json', '.jsx'],
    },
    module: {
        rules: [
            {
                test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=.*]+)?$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: 'fonts/[name].[ext]',
                    },
                }],
            },
            {
                test: /\.(jpg|png|gif)$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                        name: 'images/[name].[ext]'
                    },
                }],
            },
            {
                test: /\.html/,
                use: [{
                    loader: 'html-loader',
                    options: {
                        minimize: false,
                    },
                }],
            },
        ],
    },
    plugins: [
        new webpack.DefinePlugin(config.globals),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
        }),
        new webpack.ProgressPlugin({
            handler: (percentage, msg) => {
                const stream = process.stderr;

                if (!buildRunning) {
                    buildRunning = true;
                    startTime = new Date();
                } else if (stream.isTTY && percentage < 0.71) {
                    stream.cursorTo(0);
                    stream.write(`${chalk.magenta(`${msg} ${Math.round(percentage * 100)}%`)}`);
                    stream.clearLine(1);
                } else if (percentage === 1) {
                    const now = new Date();
                    const buildTime = `${(now - startTime) / 1000}s`;
                    console.log(chalk.green(`\nwebpack: bundle build completed in ${buildTime}.`));

                    buildRunning = false;
                }
            },
        }),
        new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    ],
};

if (__PROD__) {
    webpackConfig = getProductionConfig(webpackConfig);
} else {
    webpackConfig = getDevConfig(webpackConfig);
}


module.exports = webpackConfig;
